$(function(){
    $('#access_code').val('');
    $('#access_code').focus();
    
    
    $('#different_categories').click(function(e){
        bundle='';
        e.preventDefault();
        $('.message').hide();

        // get new ImageShield categories
        getImageshield(true);
    });
    
    $('form#access_code_form').keydown(function(e){
        if(e.keyCode == 13) {
            e.preventDefault();
            validateImageshield();  
        }
    })
    
    $('input#submit').click(function(e){
        e.preventDefault();
        validateImageshield();
    })
    
    $('#category_options').bind('click', function(){
        $('#category_options_menu').toggle(); 
        return false;
    });
})

function getImageshield(reset){
    if(reset==undefined)
        reset=false;

    $.ajax({
        type: "GET",
        url: "imageshield.php",
        data: "reset=" + reset,
        success: function(msg){
            cat1 = $(msg).find('category_name_1').text();
            cat2 = $(msg).find('category_name_2').text();
            imageURI = $(msg).find('uri').text();
            id = $(msg).find('id').text();
            
            $('.cat1').html(cat1);
            $('.cat2').html(cat2);
            $('#imageshield_id').val(id);
            
            $('#imageshield').html("<img alt='imageshield' src='" + imageURI + "' />");
        }
    });
}
 
function validateImageshield(){
    access_code = $('#access_code').val();
    id = $('#imageshield_id').val();  

    $.ajax({
        type: "POST",
        url: "validate.php",
        data: "access_code=" + access_code + "&imageshield_id=" + id,
        success: function(msg){
            result = $(msg).find('result').text();
            type = $(msg).find('type').text();
            
            if (result == 'false') {
                if (type == 'no_access_code') {
                    $('.message').html('Please enter the access code before submitting the form.').fadeOut('fast').fadeIn('slow');
                } else {
                    $('.message').html('Incorrect Access Code.  Please try again.<br/>  <small>( Remember that order matters. )</span>').fadeOut('fast').fadeIn('slow');
                    getImageshield();
                }
                $('#access_code').val('');
            }
            else {
                window.location.href = "success.php";
            }
        }
    })

}
